<template>
  <div class="products-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <el-button type="primary" @click="handleAddProduct">
            <el-icon><Plus /></el-icon>
            添加商品
          </el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="searchForm.keyword" 
              placeholder="搜索商品名称"
              clearable
              @change="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.category" placeholder="商品分类" clearable @change="handleSearch">
              <el-option label="主食" value="main" />
              <el-option label="小食" value="snack" />
              <el-option label="饮品" value="drink" />
              <el-option label="甜品" value="dessert" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="状态" clearable @change="handleSearch">
              <el-option label="上架" value="active" />
              <el-option label="下架" value="inactive" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
          </el-col>
          <el-col :span="4">
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 商品表格 -->
      <el-table :data="productList" v-loading="loading" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="image" label="图片" width="100">
          <template #default="scope">
            <el-image 
              :src="scope.row.image" 
              :alt="scope.row.name"
              style="width: 60px; height: 60px; border-radius: 8px;"
              fit="cover"
              :preview-src-list="[scope.row.image]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" width="200" />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ getCategoryText(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" label="原价" width="100">
          <template #default="scope">
            <span v-if="scope.row.originalPrice > scope.row.price" style="text-decoration: line-through; color: #999;">
              ¥{{ scope.row.originalPrice }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="sales" label="销量" width="80" />
        <el-table-column prop="storeName" label="所属店铺" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleViewProduct(scope.row)"
            >
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEditProduct(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              :type="scope.row.status === 'active' ? 'warning' : 'success'"
              size="small" 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '下架' : '上架' }}
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteProduct(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 商品详情/编辑弹窗 -->
    <el-dialog 
      v-model="productDialogVisible" 
      :title="dialogMode === 'view' ? '商品详情' : (dialogMode === 'add' ? '添加商品' : '编辑商品')"
      width="800px"
    >
      <el-form 
        ref="productFormRef"
        :model="productForm" 
        :rules="productRules"
        label-width="100px"
        :disabled="dialogMode === 'view'"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="category">
              <el-select v-model="productForm.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="主食" value="main" />
                <el-option label="小食" value="snack" />
                <el-option label="饮品" value="drink" />
                <el-option label="甜品" value="dessert" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number 
                v-model="productForm.price" 
                :min="0" 
                :precision="2" 
                style="width: 100%"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input-number 
                v-model="productForm.originalPrice" 
                :min="0" 
                :precision="2" 
                style="width: 100%"
                placeholder="请输入原价"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number 
                v-model="productForm.stock" 
                :min="0" 
                style="width: 100%"
                placeholder="请输入库存数量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属店铺" prop="storeId">
              <el-select v-model="productForm.storeId" placeholder="请选择店铺" style="width: 100%">
                <el-option 
                  v-for="store in storeList" 
                  :key="store.id" 
                  :label="store.name" 
                  :value="store.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="image-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :http-request="handleImageUpload"
          >
            <img v-if="productForm.image" :src="productForm.image" class="image" />
            <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="productForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="productForm.status">
            <el-radio label="active">上架</el-radio>
            <el-radio label="inactive">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer v-if="dialogMode !== 'view'">
        <span class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveProduct">
            {{ dialogMode === 'add' ? '添加' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const productDialogVisible = ref(false)
const dialogMode = ref('view') // view, add, edit
const productFormRef = ref()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 商品表单
const productForm = reactive({
  id: null,
  name: '',
  category: '',
  price: 0,
  originalPrice: 0,
  stock: 0,
  storeId: null,
  image: '',
  description: '',
  status: 'active'
})

// 表单验证规则
const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  storeId: [
    { required: true, message: '请选择所属店铺', trigger: 'change' }
  ]
}

// 店铺列表
const storeList = ref([
  { id: 1, name: '麦当劳(王府井店)' },
  { id: 2, name: '肯德基(三里屯店)' },
  { id: 3, name: '星巴克(国贸店)' }
])

// 商品列表
const productList = ref([
  {
    id: 1,
    name: '巨无霸套餐',
    category: 'main',
    price: 35.50,
    originalPrice: 39.90,
    stock: 100,
    sales: 256,
    storeId: 1,
    storeName: '麦当劳(王府井店)',
    image: 'https://via.placeholder.com/150',
    description: '经典巨无霸汉堡套餐，包含薯条和可乐',
    status: 'active',
    createTime: '2023-12-01 10:30:00'
  },
  {
    id: 2,
    name: '香辣鸡腿堡',
    category: 'main',
    price: 28.00,
    originalPrice: 28.00,
    stock: 80,
    sales: 189,
    storeId: 2,
    storeName: '肯德基(三里屯店)',
    image: 'https://via.placeholder.com/150',
    description: '香辣美味的鸡腿堡',
    status: 'active',
    createTime: '2023-12-02 14:20:00'
  }
])

// 获取分类类型
const getCategoryType = (category) => {
  const types = {
    main: 'primary',
    snack: 'success',
    drink: 'info',
    dessert: 'warning'
  }
  return types[category] || ''
}

// 获取分类文本
const getCategoryText = (category) => {
  const texts = {
    main: '主食',
    snack: '小食',
    drink: '饮品',
    dessert: '甜品'
  }
  return texts[category] || category
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadProductList()
}

// 重置搜索
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.category = ''
  searchForm.status = ''
  pagination.page = 1
  loadProductList()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadProductList()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadProductList()
}

// 添加商品
const handleAddProduct = () => {
  dialogMode.value = 'add'
  resetProductForm()
  productDialogVisible.value = true
}

// 查看商品详情
const handleViewProduct = (product) => {
  dialogMode.value = 'view'
  Object.assign(productForm, product)
  productDialogVisible.value = true
}

// 编辑商品
const handleEditProduct = (product) => {
  dialogMode.value = 'edit'
  Object.assign(productForm, product)
  productDialogVisible.value = true
}

// 切换商品状态
const handleToggleStatus = async (product) => {
  const action = product.status === 'active' ? '下架' : '上架'
  try {
    await ElMessageBox.confirm(
      `确认要${action}商品 "${product.name}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API
    product.status = product.status === 'active' ? 'inactive' : 'active'
    ElMessage.success(`${action}成功`)
  } catch {
    ElMessage.info('已取消操作')
  }
}

// 删除商品
const handleDeleteProduct = async (product) => {
  try {
    await ElMessageBox.confirm(
      `确认要删除商品 "${product.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // 这里应该调用API
    const index = productList.value.findIndex(item => item.id === product.id)
    if (index > -1) {
      productList.value.splice(index, 1)
    }
    
    ElMessage.success('删除成功')
  } catch {
    ElMessage.info('已取消删除')
  }
}

// 保存商品
const handleSaveProduct = async () => {
  try {
    await productFormRef.value.validate()
    
    // 这里应该调用API
    if (dialogMode.value === 'add') {
      productForm.id = Date.now()
      productForm.sales = 0
      productForm.createTime = new Date().toLocaleString()
      productForm.storeName = storeList.value.find(s => s.id === productForm.storeId)?.name || ''
      productList.value.unshift({ ...productForm })
      ElMessage.success('添加成功')
    } else {
      const index = productList.value.findIndex(item => item.id === productForm.id)
      if (index > -1) {
        productForm.storeName = storeList.value.find(s => s.id === productForm.storeId)?.name || ''
        productList.value[index] = { ...productForm }
      }
      ElMessage.success('保存成功')
    }
    
    productDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 重置表单
const resetProductForm = () => {
  Object.assign(productForm, {
    id: null,
    name: '',
    category: '',
    price: 0,
    originalPrice: 0,
    stock: 0,
    storeId: null,
    image: '',
    description: '',
    status: 'active'
  })
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 处理图片上传
const handleImageUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    
    // 调用OSS上传接口
    const response = await axios.post('/api/file/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data.success) {
      productForm.image = response.data.data.url
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error('图片上传失败: ' + response.data.message)
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
    console.error('Upload error:', error)
  }
}

// 加载商品列表
const loadProductList = async () => {
  loading.value = true
  try {
    // 这里应该调用API
    await new Promise(resolve => setTimeout(resolve, 500))
    pagination.total = productList.value.length
  } catch (error) {
    ElMessage.error('加载商品列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadProductList()
})
</script>

<style scoped>
.products-page {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.pagination-area {
  margin-top: 20px;
  text-align: center;
}

.image-uploader .image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  display: block;
}

.image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
}

.image-uploader .el-upload:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
</style> 